package com.zhangdi.zddemo.zookeeper;

import org.apache.zookeeper.AddWatchMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

public class DistConfiguration implements Watcher {
    private String db_url;
    private String db_uname;
    private String db_pwd;

    private String es_url;

    CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == Event.EventType.None) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                System.out.println("连接成功.");
                countDownLatch.countDown();
                try {
                    ZKCreate.zk.addWatch("/config", AddWatchMode.PERSISTENT);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                refresh();
            } else if (event.getState() == Event.KeeperState.Disconnected) {
                System.out.println("连接断开!");
            } else if (event.getState() == Event.KeeperState.Expired) {
                System.out.println("连接超时!");
                //todo 尝试重连
            } else if (event.getState() == Event.KeeperState.AuthFailed) {
                System.out.println("验证失败!");
            }
        } else if (event.getType() == Event.EventType.NodeDataChanged) {
            refresh();
        } else if(event.getType() == Event.EventType.NodeChildrenChanged) {
            System.out.println(event.getPath());
            refresh();
        }
    }

    public void refresh() {//一个路径只需要设置一次watch，除非手动删除watch
        System.out.println("拉取节点内容");
        try {
            Stat stat = ZKCreate.zk.exists("/config/db_url", false);
            if(null != stat) {
                this.db_url = new String(ZKCreate.zk.getData("/config/db_url", true, null));
            }
            Stat stat1 = ZKCreate.zk.exists("/config/db_uname", false);
            if(null != stat1) {
                this.db_uname = new String(ZKCreate.zk.getData("/config/db_uname", true, null));
            }
            Stat stat2 = ZKCreate.zk.exists("/config/db_pwd", false);
            if(null != stat2) {
                this.db_pwd = new String(ZKCreate.zk.getData("/config/db_pwd", true, null));
            }
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(db_url + "     " + db_uname);
    }
}
